//
//  UserInfoViewController.swift
//  ColorNote
//
//  Created by 伏文东 on 2018/2/10.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit

class UserInfoViewController: UIViewController {

    // MARK: 控件属性
    @IBOutlet weak var headPortrait: UIImageView!
    @IBOutlet weak var changeHeadBtn: UIButton!
    
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var infoTextField: UITextField!
    
    @IBAction func changeClick(_ sender: UIButton) {
        photoSelected()
    }
    
    // MARK: 定义属性
    var isPhotoChange = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: 监听方法
    @objc private func clickCencel()  {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func clickDone()  {
        kDefaults.set(nameTextField.text, forKey: "name")
        kDefaults.set(infoTextField.text, forKey: "introduce")
        if isPhotoChange {
            DataExtensions.upDataInfo(image: headPortrait.image!)
            tempbuttonAction()
            isPhotoChange = false
        }
        dismiss(animated: true, completion: nil)
    }
    
    // 通知主界面去刷新头像
    let notifiMycationName = NSNotification.Name(rawValue: "saveInfo")
    func tempbuttonAction() {
        NotificationCenter.default.post(name: notifiMycationName, object:nil)
    }
}
// MARK: - 设置UI界面
private extension UserInfoViewController {
    func setupUI()  {
        setupNaviBar()
        
        headPortrait.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(photoSelected))
        tap.numberOfTapsRequired = 1
        tap.numberOfTouchesRequired = 1
        headPortrait.addGestureRecognizer(tap)
        
        headPortrait.image = UIImage(data: info.headPortrait!)
        nameTextField.text = kDefaults.string(forKey: "name")
        infoTextField.text = kDefaults.string(forKey: "introduce")
        
        nameTextField.delegate = self
        infoTextField.delegate = self
        nameTextField.tag = 1001
        infoTextField.tag = 1002
    }
    func setupNaviBar()  {
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(clickCencel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(clickDone))
    }
}
// MARK: - 遵守相机图片协议协议
extension UserInfoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // MARK: 弹出alert
    @objc func photoSelected() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let photo = UIAlertAction(title: "相册", style: .default) { (_) in
            self.openPhotoAlbum()
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(photo)
        alert.addAction(cancel)
        present(alert, animated: true, completion: nil)
    }
    // MARK: 点击跟换头像按钮
    func openPhotoAlbum()  {
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else { return }
        let pick = UIImagePickerController()
        pick.allowsEditing = true
        pick.delegate = self
        present(pick, animated: true, completion: nil)
    }
    
    // MARK: UIImage Picker Controller Delegate 弹起相册
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerEditedImage] as? UIImage
        let size = CGSize(width: 90, height: 90)
        guard let img = UIImage.avatarImage(image: image!, size: size) else { return }
        headPortrait.image = img
        isPhotoChange = true
        
        dismiss(animated: true, completion: nil)
    }
}

// MARK: - 遵守UITextFieldDelegate协议
extension UserInfoViewController: UITextFieldDelegate {
    // 限制textField字数
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else  {return true}
        let newLenght = text.count + string.count - range.length
        if textField.tag == 1001 {
            return newLenght <= 24
        } else {
            return newLenght <= 28
        }
    }
}

































